<template>
  <div class="app-container">
    <h2 style="text-align: center">发布新课程</h2>
    <el-steps :active="1" align-center style="margin-bottom: 40px" process-status="wait">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="发布课程"></el-step>
    </el-steps>

    <el-form
      ref="courseForm"
      :model="courseInfo"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="课程标题" prop="title">
        <el-input
          v-model="courseInfo.title"
          placeholder="示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"
        />
      </el-form-item>

      <el-form-item label="课程类别" prop="subjectId">
        <!-- 课程一级分类 -->
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="请选择"
          @change="subjectLevelOneChange"
        >
          <el-option
            v-for="item in subjectNestedList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <!-- 课程二级分类 -->

        <el-select v-model="courseInfo.subjectId" placeholder="请选择">
          <el-option
            v-for="item in subSubjectList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程讲师" prop="teacherId">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option
            v-for="item in teacherList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="总课时" prop="lessonNum">
        <el-input-number
          v-model="courseInfo.lessonNum"
          controls-position="right"
          :min="1"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="课程简介" prop="description">
        <Tinymce v-model="courseInfo.description"></Tinymce>
      </el-form-item>

      <el-form-item label="课程封面" prop="cover">
        <!-- <el-input v-model="courseInfo.cover" /> -->
        <el-upload
          class="upload-demo"
          ref="upload"
          :show-file-list="false"
          :action="`${BASE_URL}/file/upload?host=cover`"
          :before-upload="beforeCoverUpload"
          :on-success="coverUploadSuccess"
          :limit="1"
        >
          <img :src="courseInfo.cover" alt="" />
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格" prop="price">
        <el-input-number
          v-model="courseInfo.price"
          controls-position="right"
          :min="0"
        ></el-input-number>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="next">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import teacherApi from "@/api/teacher";
import couresApi from "@/api/coures";
import subjectAPI from "@/api/subject";
import Tinymce from "../../components/Tinymce";
export default {
  components: {
    Tinymce,
  },
  data() {
    return {
      BASE_URL: process.env.BASE_API, //获取dev配置文件中的API地址
      courseInfo: {
        title: "",
        subjectParentId: "",
        subjectId: "",
        teacherId: "",
        lessonNum: 0,
        description: "",
        cover:
          "http://hopu-learning.oss-cn-hangzhou.aliyuncs.com/avatar_default.png",
        price: 0,
      },
      subjectNestedList: [], //一级课程分类
      teacherList: [], //讲师数据
      subSubjectList: [], //二级课程分类
      rules: {
        title: [
          { required: true, message: "请输课程标题", trigger: "blur" },
          { max: 50, message: "长度最大为50个字符", trigger: "blur" },
        ],
        lessonNum: [
          { type: "number", message: "总课时必须是数字", trigger: "blur" },
          { required: true, message: "请输入总课时", trigger: "blur" },
        ],
        subjectId: [
          { required: true, message: "请选择二级分类", trigger: "change" },
        ],
        teacherId: [
          { required: true, message: "请选择课程讲师", trigger: "change" },
        ],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    // 初始化课程分类下拉框
    initSubjectList() {
      // 调用课程分类API
      subjectAPI.getList().then((res) => {
        this.subjectNestedList = res.data;
      });
    },
    // 初始化讲师下拉框
    initTeacherList() {
      teacherApi.listTeacher().then((res) => {
        this.teacherList = res.data;
      });
    },

    beforeCoverUpload(file) {
      // console.log(file);
      // 判断文件格式
      if (file.type !== "image/jpeg") {
        this.$message.error("上传图片必须是JPG格式");
        return false;
      }
      // 判断图片大小
      if (file.size / 1024 / 1024 > 2) {
        this.$message.error("上传图片不能超过2M");
        return false;
      }
    },
    coverUploadSuccess(response, file, fileList) {
      // 根据成功后的地址为tp赋值
      // console.log(response)
      this.courseInfo.cover = response.data.ossUrl;
    },
    // 初始化当前页面
    init() {
      if (this.$route.params && this.$route.params.id) {
        // 执行更新操作
        // 根据课程id获取当前更新课程信息
        const couresId = this.$route.params.id;
        // console.log(couresId)
        this.getCourseInfo(couresId);

        // 获取讲师信息下拉框数据
        this.initTeacherList();

        // 获取课程分类
        this.initSubjectList();
      } else {
        // 执行添加操作
        // 获取一级课程分类
        this.initSubjectList();

        // 获取讲师基本信息
        this.initTeacherList();
      }
    },
    next() {
      this.$refs["courseForm"].validate((valid) => {
        if (valid) {
          // 判断执行的是更新还是添加
          if (this.courseInfo.id) {
            // 更新
            this.updataCourse()
          } else {
            // 添加
            this.addCourse();
          }
        }
      });

      // 跳转至创建课程大纲页面
      // this.$router.push({ path: "/coures/chapter" });
    },
    subjectLevelOneChange(value) {
      console.log(value);
      // 根据当前一级分类，查询二级分类
      // 找到当前一级分类id下的children
      for (let i = 0; i < this.subjectNestedList.length; i++) {
        if (this.subjectNestedList[i].id == value) {
          // 获取子集
          this.subSubjectList = this.subjectNestedList[i].children;
          // 清空查询条件中的二级分类id
          this.subjectNestedList.subjectId = "";
          return;
        }
      }
    },
    // 添加课程基本信息
    addCourse() {
      // 添加课程API
      couresApi.addCourse(this.courseInfo).then((res) => {
        // 提示成功信息
        this.$message({
          type: "success",
          message: "添加成功!",
        });
        //   跳转至课程大纲页面   通过编程式导航
     this.$router.push({ path: `/coures/chapter/${res.data}` });
      });
    },
    getCourseInfo(id) {
      //调用根据id获取课程基本信息的API
      couresApi.getCourseInfoByid(id).then((res) => {
        this.courseInfo = res.data;

        // 调用课程分类API
        subjectAPI.getList().then((res) => {
          this.subjectNestedList = res.data;

             // 根据一级分类id获取旗下的二级分类
        const parentSubject = this.subjectNestedList.find(
          (item) => item.id == this.courseInfo.subjectParentId
        );
        if (parentSubject) {
          this.subSubjectList = parentSubject.children;
        }
        });
      });
    },
    // 更新课程信息
    updataCourse(){
      couresApi.updateCourse(this.courseInfo).then(res=>{
        // 更新成功提示信息
          this.$message({
          type: "success",
          message: "修改成功!",
        });
         //   跳转至课程大纲页面   通过编程式导航
        this.$router.push({ name:"CouresChapter",params:{id:this.courseInfo.id} });
      }).catch(err=>{
        // 错误提示
          this.$message({
          type: "success",
          message: "更新失败",
        });
      })
    }
  },
};
</script>